<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/26 0026
 * Time: 17:31
 */
namespace app\manager\model;

use think\Cache;
use think\Session;

/**
 * 普通权限的文件缓存
 *
 * Class PermissionFileCache
 * @package app\manager\model
 */
class PermissionFileCache {

    const PREFIX_CACHE_PERMISSION = 'permission';

    private $_cache = null;

    private $_config = [
        // 驱动方式
        'type'   => 'file',
        // 缓存保存目录
        'path'   => '../runtime/cache/',
        // 缓存前缀
        'prefix' => 'file_cache',
        // 缓存有效期 0表示永久缓存
        'expire' => 0,
    ];

    public function __construct($config = null)
    {
        if ($config) {
            $cacheM = new Cache($config);
        } else {
            $cacheM = new Cache($this->_config);
        }
        $this->_cache = $cacheM;
    }


    public function getPermission() {
        $sessionM = new Session();
        $user = $sessionM->get('user');
        $uid = $user['uid'];

        $name = self::PREFIX_CACHE_PERMISSION . $uid;
        $permission_cache = $this->_cache->get($name);
        if ($permission_cache) { // have cache
            //var_dump('cache:', $permission_cache);die;
            return $permission_cache;
        }

        // no cache
        return false;
    }


    public function setPermission($permission) {
        $sessionM = new Session();
        $user = $sessionM->get('user');
        $uid = $user['uid'];
        //$cacheM = new Cache();
        $name = self::PREFIX_CACHE_PERMISSION . $uid;
        if ($this->_cache->set($name, $permission)) {
            return true;
        }


        // failure
        return false;
    }

    /**
     * clear permission cache
     *
     * @return bool
     */
    public function rmPermission() {
        return $this->_cache->clear();
    }

}